package co.com.javeriana.aes.oms.customer;

import co.com.javeriana.aes.oms.common.BaseBean;
import co.com.javeriana.aes.oms.common.entity.Customer;
import co.com.javeriana.aes.oms.constants.NavRules;
import co.com.javeriana.aes.oms.customer.service.CustomerServiceBeanLocal;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.UnselectEvent;

/**
 *
 * @author Jonathan Fernandez <jonathan.fvargas@gmail.com>
 */
@ManagedBean(name = "CustomerBean")
@SessionScoped
public class CustomerBean extends BaseBean {

    @EJB
    private CustomerServiceBeanLocal localservice;
    private List<Customer> dtos;
    private Customer selected;
    private String customerId;
    private boolean active;

    @PostConstruct
    public void init() {
        //if (!FacesContext.getCurrentInstance().isPostback()) {
            dtos = localservice.getCustomers();
        //}          
            
    }

    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }

    public String getCustomerId() {
        return customerId;
    }

    public void setCustomerId(String customerId) {
        this.customerId = customerId;
    }

    public Customer getSelected() {
        return selected;
    }

    public void setSelected(Customer selected) {
        this.selected = selected;
    }

    public List<Customer> getDtos() {
        return dtos;
    }

    public void setDtos(List<Customer> dtos) {
        this.dtos = dtos;
    }

    public void findCustomer() {

        try {

            if (customerId.isEmpty()) {
                init();                
            } else {

                selected = localservice.getCustomerById(Integer.valueOf(customerId));

                if (selected != null) {
                    dtos.clear();
                    dtos.add(selected);
                }

            }

        } catch (Exception e) {
            //show message no info
            addMessage("No existe el cliente consultado");
            customerId = "";
        }
    }

    public String goToDetails() {
        
        //to avoid lazy load
        Integer id = selected.getCusid();        
        selected = localservice.getCustomerById(id); 
        return NavRules.GO_TO_CUSTOMER_DETAILS.name();
    }

    public String backToMainPage() {
        return NavRules.GO_TO_CUSTOMER_BY_ID.name();
    }
    
    
    public void onRowSelect(SelectEvent event) {
        active =true;   
    }
 
    public void onRowUnselect(UnselectEvent event) {
        active =false;   
    }

}
